#include "splitter.h"
#include "output_document.h"
#include "splitter_inserter.h"
#include "utilities.h"

namespace Pdf
{
	Splitter::Splitter(std::istream &input, const std::string &password, bool fix) 
		: InputDocument( &input, password, fix )
	{	}

    Splitter::~Splitter()
    {   }

	void Splitter::savePage(std::ostream &output, const std::vector<int> &pageNumbers)
    {
		OutputDocument document( output );
        output << getHeaderVersion() << std::endl;
        output << getHeaderBinary()  << std::endl;

        ArrayFactory kidsFactory;
        for (std::vector<int>::const_iterator i = pageNumbers.begin(), end = pageNumbers.end(); i != end; ++i)
        {
            IndirectObject page = getPage( *i );
			cast<Dictionary*>( page.object )->set("Parent", getPageRoot().header );

            page.object->apply( &Inserter( &document, this ) );
			document.write( page );

            kidsFactory.append( page.header );
        }

        Dictionary::Ptr pageRoot = new Dictionary();
        pageRoot->set( "Type",  new Name("Pages") );
        pageRoot->set( "Kids",  kidsFactory.create() );
        pageRoot->set( "Count", new Integer( pageNumbers.size() ) );
        document.write( IndirectObject( getPageRoot().header, pageRoot ) );

        Dictionary::Ptr catalog = new Dictionary();
        catalog->set( "Type",  new Name("Catalog") );
        catalog->set( "Pages", getPageRoot().header );
        document.write( IndirectObject( getCatalog().header, catalog ) );

        document.getTrailer()->set( "Root", getCatalog().header );
    }
}